import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken, removeToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"];

//路由权限控制
async function permission(to, next) {
  // 开始进度条
  NProgress.start();

  //设置页面标题
  document.title = getPageTitle(to.meta.title);

  // 判断用户是否登录
  const hasToken = getToken();
  if (to.path === "/login") {
    //无论是否登录，到登录页需要放行且清空token
    removeToken();
    next();
    NProgress.done();
  } else if (hasToken) {
    // 判断动态权限路由是否加载完毕
    const hasRoles = store.getters.roles && store.getters.roles.length > 0;
    if (hasRoles) {
      //加载完毕则放行
      next();
    } else {
      //未加载完毕则请求接口获取动态路由信息，添加路由
      console.log("未加载动态路由，再加载");
      try {
        // get user info
        // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
        const { roles } = await store.dispatch("user/getInfo");
        // generate accessible routes map based on roles
        const accessRoutes = await store.dispatch(
          "permission/generateRoutes",
          roles
        );

        // 添加路由
        router.addRoutes(accessRoutes);

        // 保证路由已经加载完毕后再跳转
        next({ ...to, replace: true });
      } catch (error) {
        // 清除token，重新登录
        await store.dispatch("user/resetToken");
        Message.error(error || "Has Error");
        next(`/login`);
        NProgress.done();
      }
    }
  } else {
    /* 没有token，未登录，判断是否在免登录白名单内*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 免登录白名单则放行
      next();
    } else {
      // 重定向到登录页
      next(`/login`);
      NProgress.done();
    }
  }
}
router.beforeEach(async (to, from, next) => {
  await permission(to, next);
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
